package com.george.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  使用fastfile实现文件上传
 * </p>
 *
 * @author GeorgeChan 2019/4/19 16:12
 * @version 1.0
 * @since jdk1.8
 */
@RestController
public class ApiFileUpload {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiFileUpload.class);
    @Autowired
    private FastFileStorageClient fileStorageClient;

    /**
     * 文件上传
     * @param uploadFile 上传的文件
     * @return
     */
    @PostMapping(value = "uploadFile")
    public String uploadFile(@RequestParam MultipartFile uploadFile){
        InputStream fileInputStream = null;
        // 文件后缀
        String extension = FilenameUtils.getExtension(uploadFile.getOriginalFilename());
        try {
            fileInputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StorePath storePath = fileStorageClient.uploadFile(fileInputStream, uploadFile.getSize(), extension, null);
        LOGGER.info("文件保存路径为====》 {}", storePath);
        return storePath.toString();
    }

    /**
     * 文件批量上传
     * @param files
     * @return
     * @throws IOException
     */
    @PostMapping(value = "uploadBatchFile")
    public List<String> uploadBatchFile(@RequestParam MultipartFile[] files) throws IOException {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            StorePath storePath = fileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
            LOGGER.info("文件保存路径为====》 {}", storePath);
            list.add(storePath.toString());
        }
        return list;
    }
}
